<template>
  <div class="check-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="盘点单号">
          <el-input
            v-model="searchForm.checkCode"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
       
        <el-form-item label="盘点类型" style="width: 220px;">
          <el-select v-model="searchForm.checkType" placeholder="请选择" clearable>
            <el-option label="存货盘点" :value="1" />
            <el-option label="循环盘点" :value="2" />
            <el-option label="全面盘点" :value="3" />
          </el-select>
        </el-form-item>
       
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
         
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
     
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        style="width: 100%;" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="checkCode" label="盘点单号" width="120" />
        <el-table-column prop="checkResult" label="盘点结果" width="100">
          <template #default="scope">
            <el-tag 
              :type="getResultType(scope.row.checkResult)"
              size="small"
            >
              {{ scope.row.checkResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="depotName" label="仓库名称" min-width="120" />
        <el-table-column prop="checkType" label="盘点类型" width="100" >
          <template #default="scope">
           
              {{ formatcheckType(scope.row.checkType) }}
           
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="盘点开始时间" width="120" />
        <el-table-column prop="endTime" label="盘点结束时间" width="120" />
        <el-table-column prop="outStatus" label="出库状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.outStatus)"
              size="small"
            >
              {{ formatOutStatus(scope.row.outStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enterStatus" label="入库状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.enterStatus)"
              size="small"
            >
              {{ formatEnterStatus(scope.row.enterStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkProduct" label="盘点货品" min-width="150" />
        <el-table-column prop="checkNum" label="盘点数量" width="100" />
        <el-table-column prop="profitNum" label="盘盈数量" width="100">
          <template #default="scope">
            <span class="profit-number">{{ scope.row.profitNum }}</span>
          </template>
        </el-table-column>
       
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.PageIndex"
        v-model:page-size="pagination.PageSize"
        :total="pagination.totalCount"
        :page-sizes="[15, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import PurSale from '@/http/PurSale'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/http/axiosHelper'
// 搜索表单数据
const searchForm = reactive({
  checkCode: '',
  checkResult: '',
  checkType: ''
})

// 分页数据
const pagination = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
  totalPage: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 获取盘点结果标签类型
const getResultType = (result: string) => {
  switch (result) {
    case '草稿':
      return 'info'
    case '有盈亏':
      return 'warning'
    case '无盈亏':
      return 'success'
    default:
      return 'info'
  }
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: // 未出库/未入库
      return 'info'
    case 1: // 已出库/已入库
      return 'success'
    default:
      return 'info'
  }
}

// 格式化出库状态
const formatOutStatus = (status: number) => {
  switch (status) {
    case 0:
      return '未出库'
   
    case 1:
      return '已出库'
    default:
      return '未知'
  }
}

const formatcheckType = (checkType: number) => {
  switch (checkType) {
    case 1:
      return '存货盘点'
   
    case 2:
      return '循环盘点'
       case 3:
      return '全面盘点'
    default:
      return '未知'
  }
}

// 格式化入库状态
const formatEnterStatus = (status: number) => {
  switch (status) {
    case 0:
      return '未入库'
  
    case 1:
      return '已入库'
    default:
      return '未知'
  }
}

// 搜索方法
const handleSearch = async () => {
  loading.value = true
  try {
    const params = {
      PageIndex: pagination.PageIndex,
      PageSize: pagination.PageSize,
      CheckCode: searchForm.checkCode,
      CheckType: searchForm.checkType,
      CheckResult: searchForm.checkResult,
    
    }
    
    try {
      const response = await http.get('/scmreadconsul/api/Check/ShowCheck', { params })
      
      if (response.data.code === 200) {
        tableData.value = response.data.items || []
        pagination.totalCount = response.data.totalCount || 0
        pagination.totalPage = response.data.totalPage || 0
        ElMessage.success('查询成功')
      } else {
        ElMessage.error(response.data.msg || '查询失败')
      }
    } catch (apiError) {
      console.error('API调用失败:', apiError)
      // 如果API调用失败，使用模拟数据
      const mockData = generateMockData()
      tableData.value = mockData
      pagination.totalCount = 100
      pagination.totalPage = 10
      ElMessage.warning('使用模拟数据，API接口暂时不可用')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const mockData = []
  const checkCodes = ['PDDH870', 'PDDH871', 'PDDH872', 'PDDH873', 'PDDH874', 
                      'PDDH875', 'PDDH876', 'PDDH877', 'PDDH878', 'PDDH879']
  const checkResults = ['草稿', '有盈亏', '无盈亏', '有盈亏', '无盈亏', 
                       '无盈亏', '无盈亏', '无盈亏', '无盈亏', '无盈亏']
  const depotNames = ['货品仓库一', '货品仓库二', '货品仓库三', '货品仓库四', '货品仓库五']
  const checkTypes = ['存货盘点', '循环盘点', '全面盘点']
  const checkProducts = ['三锅头,可笑,何必等8项', '货品A,货品B等5项', '货品C,货品D等3项', 
                        '货品E,货品F等6项', '货品G,货品H等4项', '货品I,货品J等7项',
                        '货品K,货品L等2项', '货品M,货品N等9项', '货品O,货品P等1项', '货品Q,货品R等10项']
  
  for (let i = 0; i < 10; i++) {
    const outStatus = i % 3 // 0: 未出库, 1: 部分出库, 2: 已出库
    const enterStatus = i % 3 // 0: 未入库, 1: 部分入库, 2: 已入库
    
    mockData.push({
      serialNumber: i + 1,
      checkCode: checkCodes[i],
      checkResult: checkResults[i],
      depotName: depotNames[i % depotNames.length],
      checkType: checkTypes[i % checkTypes.length],
      startTime: '2024-02-29',
      endTime: '2024-02-29',
      outStatus: outStatus,
      enterStatus: enterStatus,
      checkProduct: checkProducts[i],
      checkNum: 50,
      profitNum: 50
    })
  }
  
  return mockData
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  pagination.PageIndex = 1
  handleSearch()
}

// 高级搜索
const handleAdvancedSearch = () => {
  ElMessage.info('高级搜索功能开发中...')
}

// 新增
const handleAdd = () => {
  ElMessage.info('新增功能开发中...')
}

// 删除
const handleDelete = async (row?: any) => {
  try {
    await ElMessageBox.confirm('确定要删除选中的盘点单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 作废
const handleVoid = () => {
  ElMessage.info('作废功能开发中...')
}

// 锁定仓库
const handleLockWarehouse = () => {
  ElMessage.info('锁定仓库功能开发中...')
}

// 刷新数据
const handleRefresh = () => {
  handleSearch()
}

// 编辑
const handleEdit = (row: any) => {
  ElMessage.info(`编辑盘点单: ${row.checkCode}`)
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.PageSize = size
  pagination.PageIndex = 1
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.PageIndex = page
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 组件挂载时加载数据
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.check-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: flex-end;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 10px;
}

.profit-number {
  font-weight: bold;
  color: #67c23a;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .check-container {
    padding: 10px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
  
  .action-buttons .el-button {
    margin-bottom: 5px;
  }
}
</style> 